package api

import (
	"context"

	"fmt"
	"io"
	"os"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
	"github.com/docker/go-connections/nat"
	"github.com/gin-gonic/gin"
)

func ImagesList(c *gin.Context) {
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	images, err := cli.ImageList(ctx, types.ImageListOptions{})
	if err != nil {
		panic(err)
	}

	c.JSON(200, gin.H{"code": 0, "message": "镜像列表", "data": images})
}

func ImageRemove(c *gin.Context) {
	imageId := c.Query("imageId")
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	imageDelete, err := cli.ImageRemove(ctx, imageId, types.ImageRemoveOptions{})
	if err != nil {
		fmt.Println(err)
		c.JSON(200, gin.H{"code": 1, "message": err.Error()})
		return
	}

	c.JSON(200, gin.H{"code": 0, "message": "镜像删除成功", "data": imageDelete})
}

func ImagePull(c *gin.Context) {
	name := c.Query("name")
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	out, err := cli.ImagePull(ctx, name, types.ImagePullOptions{})
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "message": "镜像拉取失败"})
	}
	defer out.Close()
	io.Copy(os.Stdout, out)

	c.JSON(200, gin.H{"code": 0, "message": "镜像拉取成功"})
}

func ContainerCreate(c *gin.Context) {
	containerName := c.Query("containerName")

	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	config := container.Config{}
	var s3 []string = make([]string, 1)
	s3[0] = "mysqld"

	config.Cmd = s3
	config.Image = "mysql:5.6"

	var env []string = make([]string, 1)
	env[0] = "MYSQL_ROOT_PASSWORD=123456"
	config.Env = env

	hostConfig := container.HostConfig{}

	a := make(nat.PortMap, 10)
	b := make([]nat.PortBinding, 10)
	b[0].HostPort = "3308"
	a["3306/tcp"] = b
	hostConfig.PortBindings = a
	body, err := cli.ContainerCreate(ctx, &config, &hostConfig, nil, nil, containerName)
	if err != nil {
		fmt.Println(err)
		c.JSON(200, gin.H{"code": 1, "message": "镜像拉取失败"})
		return
	}

	c.JSON(200, gin.H{"code": 0, "message": "镜像拉取成功", "body": body})
}
